<?php


namespace models\Business;


use models\DAO\AlibabaproductModel;
use models\Exception\Business\AlibabacategoryException;
use models\Exception\Business\AlibabaproductException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\AlibabacategoryService;
use models\Service\AlibabaproductService;
use models\Service\AlibabashippingService;
use models\Service\SystemService;
use Task\client;
use Yaf\Exception;
use Yaf\Registry;

class AlibabaProduct
{
    /**
     * 修改点击量
     * @param $product
     * @param string $type
     * @return bool
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function updateClicks($product, $type = 'alibaba') {
        $product_clicks_cache_name = $type . '_product_clicks:' . $product['product_id'];
        $redis = Registry::get('redis');
        try {
            $redis->ping();
        } catch (\Exception $e) {
            $redis->auth(Registry::get('config')['redis']['master']['auth']);
        }
        $redis->select(7);
        $product['clicks'] = $redis->incrBy($product_clicks_cache_name, 1);

//        $product_cache_name = $type . '_product:' . $product['product_id'];
//        Registry::get('redis_string')->updateString($product_cache_name, json_encode($product));

        if ($type == 'alibaba') {

//            AlibabaProduct::editProduct(['product_id' => $product['product_id'], 'clicks' => $product['clicks']]);
        }

        return true;
    }

    static public function updateViews($products = []) {
        $product_views_arr = array_column($products['data'], 'views', 'product_id');
//        $product_arr = array_column($products['data'], null, 'product_id');

        if (empty($product_views_arr))
            return false;

        $redis = Registry::get('redis');
        try {
            $redis->ping();
        } catch (\Exception $e) {
            $redis->auth(Registry::get('config')['redis']['master']['auth']);
        }
        $redis->pipeline();
        foreach ($product_views_arr as $product_id => $views) {
            $redis->select(7);
            $product_views_cache_name = 'alibaba_product_views:' . $product_id;
            $redis->incrBy($product_views_cache_name, 1);
        }
        $redis->exec();

        return true;
//        $product['clicks'] = $redis->incrBy($product_cache_name, 1);

        /*$client = new client();
        try {
            // 记录曝光量
            $product_views_arr = array_column($products['data'], 'views', 'product_id');

            $client->connect();
            if (!empty($product_views_arr))
                $client->updateProductViews($product_views_arr);
        } catch (Exception $e) {

        } finally {
            $client->close();
        }*/
    }

    /**
     * @param array $modules_list
     * @return array
     */
    static public function getProductByModules($modules_list = [])
    {
        $product = $product_id_info_arr = $product_sku_id_arr = [];
        try {
            $product_id_arr = array_column($modules_list['data'], 'product_id');
            $product_id_arr = array_filter(array_unique($product_id_arr));

            if (count($product_id_arr) == 1)
                $product = AlibabaProduct::getProduct(['id' => implode('', $product_id_arr), 'from_api' => true]);
            else if (count($product_id_arr) > 1)
                $product = AlibabaProduct::getProductList(['page' => 1, 'page_size' => count($product_id_arr),
                                                           'sort' => 'desc', 'order' => 'product_id', 'product_id' => $product_id_arr, 'from_api' => true]);
            $product_id_info_arr = array_column($product['data'], null, 'product_id');
            $sku_arr = array_column($product['data'], 'sku', 'product_id');
            foreach ($sku_arr as $product_id => $product_info)
                $product_sku_id_arr[$product_id] = array_column($product_info, null, 'sku_id');

        } catch (\Exception $e) {

        } finally {
            foreach ($modules_list['data'] as $k => $v) {
                $modules_list['data'][$k]['product_info'] = isset($product_id_info_arr[$v['product_id']]) ? $product_id_info_arr[$v['product_id']] : [];
                $modules_list['data'][$k]['product_info']['sku'] = [];
                foreach (explode(',', $v['sku_id']) as $sku_id) {
                    if (isset($product_sku_id_arr[$v['product_id']][$sku_id])) {
                        array_push($modules_list['data'][$k]['product_info']['sku'], $product_sku_id_arr[$v['product_id']][$sku_id]);
                    }
                }
            }
            return $modules_list;
        }
    }

    /**
     * 删除商品主图、主视频
     * @param array $parameters
     * @return bool
     */
    static public function deleteMainImageVideo($parameters = [])
    {
        if (strpos($parameters['url'], Registry::get('config')['application']['host']) !== false)
            $file = str_replace(Registry::get('config')['application']['host'], APP_PATH . '/public', $parameters['url']);
        else
            $file = $parameters['url'];

        Registry::get('alibaba_log')->err('file: ' . $file);
        Registry::get('alibaba_log')->err('file: ' . json_encode(file_exists($file)));

        if (file_exists($file))
            unlink($file);

        return true;
    }

    /**
     * @param $parameters
     * @return array
     * @throws AlibabacategoryException
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getProduct($parameters)
    {
        if (!isset($parameters['id']) || empty($parameters['id']))
            throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY, AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY_NO);

        $from_api = false;
        if (isset($parameters['from_api']) && $parameters['from_api'] === true)
            $from_api = true;

        $product_info = AlibabaproductService::getInstance()->getOne($parameters['id']);
        if (empty($product_info))
            throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);
//        $product['main_video'] = !empty($product['main_video']) && (strpos($product['main_video'], 'http://') === false ||
//            strpos($product['main_video'], 'https://') === false) ? Registry::get('config')['application']['host'] . $product['main_video'] : $product['main_video'];
        if (strpos($product_info['images'], 'http://') === false && strpos($product_info['images'], 'https://') === false) {
            $product_info['images'] = str_replace('/upload', Registry::get('config')['application']['host'] . '/upload', $product_info['images']);
        } else {
            if (strpos($product_info['images'], '_.webp') === false) {
                $product_info['images'] = $product_info['images'] . ',';
                $product_info['images'] = str_replace(['.jpg,', '.png,', '.jpeg,', '.gif,'],
                    ['.jpg_.webp,', '.png_.webp,', '.jpeg_.webp,', '.gif_.webp,'], $product_info['images']);
                $product_info['images'] = substr($product_info['images'], 0, strrpos($product_info['images'], ','));
            }
        }
        if (strpos($product_info['main_video'], 'http://') === false && strpos($product_info['main_video'], 'https://') === false) {
            $product_info['main_video'] = str_replace('/upload', Registry::get('config')['application']['host'] . '/upload', $product_info['main_video']);
        }
        if (strpos($product_info['img_url'], 'http://') === false && strpos($product_info['img_url'], 'https://') === false) {
            $product_info['img_url'] = str_replace('/upload', Registry::get('config')['application']['host'] . '/upload', $product_info['img_url']);
        } else {
            if (strpos($product_info['img_url'], '_.webp') === false)
                $product_info['img_url'] = str_replace(['.jpg', '.png', '.jpeg', '.gif'],
                    ['.jpg_.webp', '.png_.webp', '.jpeg_.webp', '.gif_.webp'], $product_info['img_url']);
        }
        $product['data'][] = $product_info;

        // 查询sku
        $product = AlibabaSku::getSkuByModules($product);


        if ($from_api === false) {
            $product = AlibabaCategory::getCategoriesByModules($product);

            // 查询活动
            if ($product['data'][0]['channel_price']) {

            }

            $parent_arr = AlibabaCategory::getAllParentsByParentId($product['data'][0]['category_id']);

            $product['data'][0]['top_parent_id']   = $parent_arr[0]['id'];
            $product['data'][0]['top_parent_name'] = $parent_arr[0]['name'];
            $product['data'][0]['sub_parent_id']   = $parent_arr[1]['id'];
            $product['data'][0]['sub_parent_name'] = $parent_arr[1]['name'];
            if (count($parent_arr) == 3) {
                $product['data'][0]['leaf_parent_id']   = $parent_arr[2]['id'];
                $product['data'][0]['leaf_parent_name'] = $parent_arr[2]['name'];
            }

        } else {
            $product['data'][0]['price_ranges'] = !is_null(json_decode($product['data'][0]['price_ranges'], true)) ?
                json_decode($product['data'][0]['price_ranges'], true) : [];

            $product = self::getRealPlatformPrice($product);

            $product['data'][0]['favours'] += $product['data'][0]['fake_favours'];
            unset($product['data'][0]['fake_favours']);
            $product['data'][0]['clicks'] += $product['data'][0]['fake_clicks'];
            unset($product['data'][0]['fake_clicks']);
            $product['data'][0]['views'] += $product['data'][0]['fake_views'];
            unset($product['data'][0]['fake_views']);
            $product['data'][0]['platform_sales'] += $product['data'][0]['fake_platform_sales'];
            unset($product['data'][0]['fake_platform_sales']);
            $product['data'][0]['sales'] = $product['data'][0]['platform_sales'];
        }

        return $product;
    }

    /**
     * 获取平台售价
     * @param array $product_data_arr
     * @return array
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getRealPlatformPrice($product_data_arr = [])
    {
        $system            = SystemService::getInstance()->getOne(1);
        $system_price_rate = $system['alibaba_price'] ? $system['alibaba_price'] : 400;
        $parent_rebate_rate = $system['parent_rate'] ? $system['parent_rate'] : 0.00;
        $grand_rebate_rate = $system['sub_rate'] ? $system['sub_rate'] : 0.00;
        $integral_rate = $system['integral_rate'] ? $system['integral_rate'] : 100;
//        $default_post_fee = $system['default_post_fee'] ? $system['default_post_fee'] : 6.00;
        $default_post_fee = 0.00;

        $real_price = '0.00';

        foreach ($product_data_arr['data'] as $index => $single_product) {
            $price_ranges_arr = [];
            $price_rate       = $single_product['platform_price'] !== '0.00' ? $single_product['platform_price'] : $system_price_rate;
            $rebate_rate = $single_product['rebate_integral'] != '0.00' ? $single_product['rebate_integral'] : $system['rebate_rate'];
            $parent_rebate_rate = $single_product['parent_rebate_integral'] != '0.00' ? $single_product['parent_rebate_integral'] : $parent_rebate_rate;
            $grand_rebate_rate = $single_product['sub_rebate_integral'] != '0.00' ? $single_product['sub_rebate_integral'] : $grand_rebate_rate;

            // 商品存在price字段
            if ($single_product['price'] !== '0.00') {
                $product_data_arr['data'][$index]['platform_price'] = $product_data_arr['data'][$index]['price'] = sprintf('%.2f', $price_rate / 100 * $single_product['price']);
                // 金豆的单位是分 商品价格的单位是元 因此此处需要再*100
//                $product_data_arr['data'][$index]['rebate_integral'] = intval($product_data_arr['data'][$index]['price']  * $rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['parent_rebate'] = intval($product_data_arr['data'][$index]['price'] * $parent_rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['grand_parent_rebate'] = intval($product_data_arr['data'][$index]['price'] * $grand_rebate_rate / 100 * 100);
            }
            // 商品存在"CPS建议价"，最终售价 = price_rate / 100 * CPS建议价
            if ($single_product['cps_suggest_price'] !== '0.00') {
                $product_data_arr['data'][$index]['platform_price'] = $product_data_arr['data'][$index]['cps_suggest_price'] = sprintf('%.2f', $price_rate / 100 * $single_product['cps_suggest_price']);
                // 金豆的单位是分 商品价格的单位是元 因此此处需要再*100
//                $product_data_arr['data'][$index]['rebate_integral'] = intval($product_data_arr['data'][$index]['cps_suggest_price'] * $rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['parent_rebate'] = intval($product_data_arr['data'][$index]['cps_suggest_price'] * $parent_rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['grand_parent_rebate'] = intval($product_data_arr['data'][$index]['cps_suggest_price'] * $grand_rebate_rate / 100 * 100);
            }
            if ($single_product['consign_price'] !== '0.00') {
                $real_price = $price_rate / 100 * $single_product['consign_price'];
                $product_data_arr['data'][$index]['platform_price'] = $product_data_arr['data'][$index]['consign_price'] = sprintf('%.2f', $real_price);
            }
            // 商品存在"超买价"，最终售价 = price_rate / 100 * 超买价
            if ($single_product['promotion_price'] !== '0.00') {
                $product_data_arr['data'][$index]['platform_price'] = $product_data_arr['data'][$index]['promotion_price'] = sprintf('%.2f', $price_rate / 100 * $single_product['promotion_price']);
                // 金豆的单位是分 商品价格的单位是元 因此此处需要再*100
//                $product_data_arr['data'][$index]['rebate_integral'] = intval($product_data_arr['data'][$index]['promotion_price'] * $rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['parent_rebate'] = intval($product_data_arr['data'][$index]['promotion_price'] * $parent_rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['grand_parent_rebate'] = intval($product_data_arr['data'][$index]['promotion_price'] * $grand_rebate_rate / 100 * 100);
            }
            // 商品存在"渠道专享价"，最终售价 = price_rate / 100 * 渠道专享价
            if ($single_product['channel_price'] !== '0.00') {
                $product_data_arr['data'][$index]['platform_price'] = $product_data_arr['data'][$index]['channel_price'] = sprintf('%.2f', $price_rate / 100 * $single_product['channel_price']);
                // 金豆的单位是分 商品价格的单位是元 因此此处需要再*100
//                $product_data_arr['data'][$index]['rebate_integral'] = intval($product_data_arr['data'][$index]['channel_price'] * $rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['parent_rebate'] = intval($product_data_arr['data'][$index]['channel_price'] * $parent_rebate_rate / 100 * 100);
//                $product_data_arr['data'][$index]['grand_parent_rebate'] = intval($product_data_arr['data'][$index]['channel_price'] * $grand_rebate_rate / 100 * 100);
            }
            // 商品存在"sku建议零售价"，最终售价 = price_rate / 100 * 最低sku建议零售价 - price_rate / 100 * 最高sku建议零售价
            // 商品存在"sku分销基准价"，最终售价 = price_rate / 100 * 最低sku分销基准价 - price_rate / 100 * 最高sku分销基准价
            if (isset($single_product['sku']) && is_array($single_product['sku'])) {
                /*$sku_retail_price_arr = array_column($single_product['sku'], 'retail_price');
                $sku_consign_price_arr = array_column($single_product['sku'], 'consign_price');
                foreach ($sku_retail_price_arr as $idx => $retail_price) {
                    if ($retail_price !== '0.00') {
                        array_push($price_ranges_arr, $price_rate / 100 * $retail_price);
                    } else if ($sku_consign_price_arr[$idx] !== '0.00') {
                        array_push($price_ranges_arr, $price_rate / 100 * $sku_consign_price_arr[$idx]);
                    }
                }*/
                foreach ($single_product['sku'] as $idx => $sku_info) {
                    if ($sku_info['retail_price'] !== '0.00') {
                        $product_data_arr['data'][$index]['sku'][$idx]['platform_price'] =
                        $product_data_arr['data'][$index]['sku'][$idx]['retail_price'] = sprintf('%.2f', $price_rate / 100 * $sku_info['retail_price']) + $default_post_fee;
                        $product_data_arr['data'][$index]['sku'][$idx]['integral'] = (string)intval($product_data_arr['data'][$index]['sku'][$idx]['platform_price'] * $integral_rate);
                    }
                    if ($sku_info['price'] !== '0.00') {
                        $product_data_arr['data'][$index]['sku'][$idx]['platform_price'] =
                        $product_data_arr['data'][$index]['sku'][$idx]['price'] = sprintf('%.2f', $price_rate / 100 * $sku_info['price']) + $default_post_fee;
                        $product_data_arr['data'][$index]['sku'][$idx]['integral'] = intval($product_data_arr['data'][$index]['sku'][$idx]['platform_price'] * $integral_rate);
                    }
                    if ($sku_info['consign_price'] !== '0.00') {
                        $product_data_arr['data'][$index]['sku'][$idx]['platform_price'] =
                        $product_data_arr['data'][$index]['sku'][$idx]['consign_price'] = sprintf('%.2f', $price_rate / 100 * $sku_info['consign_price']) + $default_post_fee;
                        $product_data_arr['data'][$index]['sku'][$idx]['integral'] = intval($product_data_arr['data'][$index]['sku'][$idx]['platform_price'] * $integral_rate);
                    }
                }
            }
            // 商品存在"区间价格"，最终售价 = price_rate / 100 * 最低价格 - price_rate / 100 * 最高价格
            if (isset($single_product['price_ranges']) && is_array($single_product['price_ranges'])) {
                $price_ranges_arr = [];
                foreach ($single_product['price_ranges'] as $idx => $price_range) {
                    $product_data_arr['data'][$index]['price_ranges'][$idx]['price'] = sprintf('%.2f', $price_rate / 100 * $price_range['price']);
//                    array_push($price_ranges_arr, $price_rate / 100 * $price_range['price']);
                }
            }
            // 商品存在reference_price字段
//            if ($single_product['reference_price'] !== '0.00') {
//                $reference_price_arr = [];
//                foreach (explode('~', $product_data_arr['data'][$index]['reference_price']) as $reference_price) {
//                    array_push($reference_price_arr, sprintf('%.2f', $price_rate / 100 * $reference_price));
//                    $product_data_arr['data'][$index]['reference_price'] = sprintf('%.2f', $price_rate / 100 * $single_product['reference_price']);
//                    $product_data_arr['data'][$index]['rebate_integral'] = intval($product_data_arr['data'][$index]['reference_price'] * $rebate_rate / 100);
//                    $product_data_arr['data'][$index]['parent_rebate'] = intval($product_data_arr['data'][$index]['reference_price'] * $parent_rebate_rate / 100);
//                    $product_data_arr['data'][$index]['grand_parent_rebate'] = intval($product_data_arr['data'][$index]['reference_price'] * $grand_rebate_rate / 100);
//                }
//
//                if (!empty($reference_price_arr))
//                    $product_data_arr['data'][$index]['reference_price'] = implode('~', $reference_price_arr);
//            }

            /*if (! empty($price_ranges_arr)) {
                $product_data_arr['data'][$index]['platform_price'] = sprintf('%.2f', min($price_ranges_arr)) . '-' . sprintf('%.2f', max($price_ranges_arr));
            } else if ($real_price !== '0.00') {
                $product_data_arr['data'][$index]['platform_price'] = sprintf('%.2f', $real_price);
            }
            // 商品使用"分销基准价"，最终售价 = price_rate / 100 * 分销基准价
            else {*/
            /*}*/

            if ($single_product['redemption'] == 1 && $product_data_arr['data'][$index]['integral'] == 0) {
                $product_data_arr['data'][$index]['integral'] = $product_data_arr['data'][$index]['platform_price'] * $integral_rate;
            }
            $product_data_arr['data'][$index]['platform_price'] = sprintf('%.2f', $product_data_arr['data'][$index]['platform_price'] + $default_post_fee);
            $product_data_arr['data'][$index]['rebate_integral'] = (string)intval($product_data_arr['data'][$index]['platform_price'] * $rebate_rate / 100 * 100);
            $product_data_arr['data'][$index]['parent_rebate'] = (string)intval($product_data_arr['data'][$index]['platform_price'] * $parent_rebate_rate / 100 * 100);
            $product_data_arr['data'][$index]['grand_parent_rebate'] = (string)intval($product_data_arr['data'][$index]['platform_price'] * $grand_rebate_rate / 100 * 100);

            // 修改商品最小起订量，防止前客户端判断商品起订量
            $product_data_arr['data'][$index]['min_order_quantity'] = 1;
        }

        return $product_data_arr;
    }

    /**
     * 根据销量、评分排序的产品列表
     * @param array $parameters
     * @return array
     * @throws AlibabacategoryException
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getProductByScoreOrSales($parameters = []) {
        $from_api = false;
        if (isset($parameters['from_api']) && $parameters['from_api'] === true)
            $from_api = true;
        $where_arr = $order_arr = [];
        $start_pos = 0;
        $end_pos = 10;

        if (isset($parameters['parent']) && !empty($parameters['parent'])) {
            // 判断是否是叶级类目
            $category = AlibabacategoryService::getInstance()->getOne($parameters['parent']);
            if (empty($category))
                throw new AlibabacategoryException(AlibabacategoryException::ALIBABACATEGORY_IS_NOT_EXISTS, AlibabacategoryException::ALIBABACATEGORY_IS_NOT_EXISTS_NO);
            if ($category['publishing'] == 0)
                array_push($where_arr, '`category_id` in ("' . implode('", "', AlibabaCategory::getAllLeafCategoryByParentId($parameters['parent'])) . '")');
            else
                array_push($where_arr, '`category_id` = "' . $parameters['parent'] . '"');
        }

        if ($from_api === true)
            array_push($where_arr, '`stats` = 1');

        if (isset($parameters['category']))
            array_push($where_arr, '`category_id` = "' . $parameters['category'] . '"');

        if (isset($parameters['recommend']))
            array_push($where_arr, '`recommennd` = "' . $parameters['recommend'] . '"');

        if (isset($parameters['redemption']))
            array_push($where_arr, '`redemption` = "' . $parameters['redemption'] . '"');

        if (isset($parameters['keyword'])) {
            if (strpos($parameters['keyword'], ' ') === false)
                array_push($where_arr, '`title` like "%' . $parameters['keyword'] . '%"');
            else {
                $like_arr = [];
                foreach (explode(' ', $parameters['keyword']) as $keyword) {
                    array_push($like_arr, '`title` like "%' . $keyword . '%"');
                }
                if (!empty($like_arr))
                    array_push($where_arr, '(' . implode(' OR ', $like_arr) . ')');
            }
        }

        $count_sql = 'SELECT count(`product_id`) AS total FROM `alibabaproduct`' . (!empty($where_arr) ? ' WHERE ' . implode(' AND ', $where_arr) : '');
        $model = AlibabaproductModel::getInstance();
        $model->page = isset($parameters['page']) ? $parameters['page'] : 1;
        $model->page_size = isset($parameters['page_size']) ? $parameters['page_size'] : 10;
        $count = $model->query($count_sql);

        if (is_array($count) && !empty($count) && isset($count[0]['total']) && $count[0]['total'] > 0) {
            $model->genMeta($count[0]['total']);

            $start_pos = ($model->meta->current_page - 1) * $model->meta->per_page;
            $end_pos = $model->meta->per_page;
        }


        $sql = "SELECT `product_id`, `category_id`, `title`, `price`, `promotion_price`, `img_url`, `images`, `channel_price`, ".
            "`sales`, `reference_price`, `supplier_login_id`, `main_video`, `product_cargo_number`, `alibaba_stats`, " .
            "`stats`, `redemption`, `integral`, `quality_level`, `support_online_trade`, `mix_whole_sale`, `price_auth`," .
            "`price_ranges`, `amount_on_sale`, `unit`, `min_order_quantity`, `batch_number`, `sell_unit`, `quote_type`," .
            "`consign_price`, `cps_suggest_price`, `platform_price`, `recommennd`, `platform_sales`, ".
            "`fake_platform_sales`, `sales_in_30_days`, `fake_favours`, `favours`, `fake_views`, `views`, `fake_clicks`, ".
            "`clicks`, `created_at`, `updated_at`, `rebate_integral`, `parent_rebate_integral`, `sub_rebate_integral`, ";
        $order = isset($parameters['order']) && !empty($parameters['order']) ? $parameters['order'] : 'score';

        $attach_order_arr = [];
        if ($order === 'platform_price') {
            $system = System::getSystemInfo(1);
            $real_platform_price = 'IF(`platform_price` > 0, `platform_price`, IF(`promotion_price` > 0, `promotion_price`, IF(`channel_price` > 0, `channel_price`, IF(`cps_suggest_price` > 0, `cps_suggest_price`, IF(`consign_price` > 0, `consign_price`, IF(`price` > 0, `price`, 0)))))) * ' . $system['alibaba_price'] / 100 . ' AS platform_price_4_sort,';
//            $sql = str_replace('`platform_price`', $real_platform_price, $sql);
            $sql .= $real_platform_price;
            array_push($order_arr, '`platform_price_4_sort`');
            array_push($where_arr, '`price` > 0');
        } else {
            list($price_score_arr, $sales_score_arr, $sales_in_30_days_score, $favour_score_arr,
                $view_click_conversion_score_arr, $click_order_conversion_score_arr) = System::getScoreRules();

            if (!empty($sales_in_30_days_score)) {
                array_multisort(array_column($sales_in_30_days_score, 'sales_in_30_days'), SORT_ASC, $sales_in_30_days_score);
                $sql .= self::sqlIfTailRecursion($sales_in_30_days_score, ' > ', '`sales_in_30_days`', 0, '') . ' AS sales_in_30_days_score, ';
                array_push($order_arr, '`sales_in_30_days_score`');
            }

            // 点击量/下单量评分规则
            if ($order === 'score' && !empty($click_order_conversion_score_arr)) {
                array_multisort(array_column($click_order_conversion_score_arr, 'platform_sales/clicks'), SORT_ASC, $click_order_conversion_score_arr);
                $sql .= self::sqlIfTailRecursion($click_order_conversion_score_arr, ' > ', 'platform_sales/clicks', 0, '') . ' AS order_score, ';
                array_push($order_arr, '`order_score`');
                array_push($attach_order_arr, '`order_score` DESC');
            }

            // 按照价格评分 价格区间1-10的+5分；价格11-40的+10分，价格41-60的+8分，价格61-100的+4分，价格101-300的+2分，价格大于301的+1分
            if ($order === 'score' && !empty($price_score_arr)) {
                array_multisort(array_column($price_score_arr, 'price'), SORT_DESC, $price_score_arr);
                $sql .= self::sqlIfTailRecursion($price_score_arr, ' < ', '`price`', 1, '') . ' AS price_score, ';
                array_push($order_arr, '`price_score`');
            }

            // 收藏评分规则
            if ($order === 'score' && !empty($favours_score_arr)) {
                array_multisort(array_column($favours_score_arr, 'favours'), SORT_ASC, $favours_score_arr);
                $sql .= self::sqlIfTailRecursion($favours_score_arr, ' > ', '`favours`', 0, '') . ' AS favours_score, ';
                array_push($order_arr, '`favours_score`');
            }

            // 曝光量/点击量评分规则
            if ($order === 'score' && !empty($view_click_conversion_score_arr)) {
                array_multisort(array_column($view_click_conversion_score_arr, 'clicks/views'), SORT_ASC, $view_click_conversion_score_arr);
                $sql .= self::sqlIfTailRecursion($view_click_conversion_score_arr, ' > ', 'clicks/views', 0, '') . ' AS click_score, ';
                array_push($order_arr, '`click_score`');
            }

            if (!empty($sales_score_arr)) {
                array_multisort(array_column($sales_score_arr, 'sales'), SORT_ASC, $sales_score_arr);
                $sql .= self::sqlIfTailRecursion($sales_score_arr, ' > ', '`sales`', 0, '') . ' AS sales_score, ';
                array_push($order_arr, '`sales_score`');
                array_push($attach_order_arr, '`platform_sales` DESC');
            }

            array_push($attach_order_arr, '`created_at` DESC');
        }

        if (empty($sql))
            throw new ModelSqlException(ModelSqlException::BASE_MODEL_EMPTY_SQL, 400);

        $sql = substr($sql, 0, strrpos($sql, ',')) . ' FROM `alibabaproduct` ' .
            (!empty($where_arr) ? ' WHERE ' . implode(' AND ', $where_arr) : '') .
            (!empty($order_arr) ? ' ORDER BY ' . implode('+', $order_arr) . ' ' . $parameters['sort'] : '') .
            (!empty($attach_order_arr) ? ',' . implode(', ', $attach_order_arr) : '') .
            ' LIMIT ' . $start_pos . ', ' . $end_pos;

        Registry::get('db_log')->debug("dd: $sql");
//        exit($sql);
        $result = $model->query($sql);
        $model->setModelProperty($result, true);

        if (empty($model->data))
            throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_NOT_EXISTS_NO);

        $product = [
            'data' => $model->data,
            'meta' => $model->meta
        ];

        if ($from_api === true) {
            // 去除掉评分 返回的收藏量、点击量、浏览量、平台交易量均为假量+真量
            foreach ($product['data'] as $idx => $product_info) {
                if (is_null($product_info['images']))
                    $product['data'][$idx]['images'] = '';
                else {
                    if (strpos($product_info['images'], 'http://') === false && strpos($product_info['images'], 'https://') === false)
                        $product['data'][$idx]['images'] = Registry::get('config')['application']['host'] . $product_info['images'];
                    else {
                        $product_info['images'] = $product_info['images'] . ',';
                        if (strpos($product_info['data'][$idx]['images'], '_.webp') === false)
                            $product['data'][$idx]['images'] = str_replace(['.jpg,', '.png,', '.jpeg,', '.gif,'],
                                ['.jpg_.webp,', '.png_.webp,', '.jpeg_.webp,', '.gif_.webp,'], $product_info['images']);
                        $product['data'][$idx]['images'] = substr($product['data'][$idx]['images'], 0, strrpos($product['data'][$idx]['images'], ','));
                    }
                }
                if (strpos($product_info['img_url'], 'http://') === false && strpos($product_info['img_url'], 'https://') === false)
                    $product['data'][$idx]['img_url'] = Registry::get('config')['application']['host'] . $product_info['img_url'];
                else {
                    if (strpos($product_info['img_url'], '_.webp') === false)
                        $product['data'][$idx]['img_url'] = str_replace(['.jpg', '.png', '.jpeg', '.gif'],
                            ['.jpg_.webp', '.png_.webp', '.jpeg_.webp', '.gif_.webp'], $product_info['img_url']);
                }
                if (null !== json_decode($product_info['price_ranges'], true))
                    $product['data'][$idx]['price_ranges'] = json_decode($product_info['price_ranges'], true);
                else
                    $product['data'][$idx]['price_ranges'] = [];

                unset($product['data'][$idx]['price_score']);
                unset($product['data'][$idx]['sales_score']);
                unset($product['data'][$idx]['favours_score']);
                unset($product['data'][$idx]['sales_in_30_days_score']);
                unset($product['data'][$idx]['click_score']);
                unset($product['data'][$idx]['order_score']);
                $product['data'][$idx]['favours'] += $product['data'][$idx]['fake_favours'];
                unset($product['data'][$idx]['fake_favours']);
                $product['data'][$idx]['clicks'] += $product['data'][$idx]['fake_clicks'];
                unset($product['data'][$idx]['fake_clicks']);
                $product['data'][$idx]['views'] += $product['data'][$idx]['fake_views'];
                unset($product['data'][$idx]['fake_views']);
                $product['data'][$idx]['platform_sales'] += $product['data'][$idx]['fake_platform_sales'];
                unset($product['data'][$idx]['fake_platform_sales']);
                $product['data'][$idx]['sales'] = $product['data'][$idx]['platform_sales'];
            }

            // 处理价格
            $product = self::getRealPlatformPrice($product);
            // 处理是否收藏
            $product = Member::getFavoursByProductLists($product);
        }

        return $product;
    }

    /**
     * 尾递归 用以生成sql的多重if
     * 例: if(column > a, b, if(column > c, d, e))
     * @param array $column_arr
     * @param string $operation
     * @param string $column_name
     * @param int $default_value
     * @param string $str
     * @param bool $recursion
     * @return string
     */
    static public function sqlIfTailRecursion($column_arr = [], $operation = '<', $column_name = '`price`', $default_value = 1, $str = '', $recursion = true) {
        $target = array_shift($column_arr);

        // if(`column_nam` operation $price_score_arr[column_name], $price_score_arr[column_name] * coefficient, $str/$default_score)
        $str = 'IF(' . $column_name . $operation . $target[str_replace('`', '', $column_name)] . ', ' .
            (($target['number'] == 0 ? $column_name : $target['number']) . ($target['coefficient'] === 1 ? '' : '*' . $target['coefficient'])). ', '.
            (!empty($str) ? $str : $default_value) .')';
        if (count($column_arr) > 0) {
            if ($recursion === true)
                return self::sqlIfTailRecursion($column_arr, $operation, $column_name, $default_value, $str);
            else
                return $str;
        }
        else
            return $str;
    }

    /**
     * 获取商品列表
     * @param array $parameters
     * @return array|mixed
     * @throws AlibabacategoryException
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getProductList($parameters = [])
    {
        try {
            $from_api = false;
            if (isset($parameters['from_api']) && $parameters['from_api'] === true)
                $from_api = true;
            $rules = $condition = $groups = [];
            if (isset($parameters['product_id'])) {
                if (is_array($parameters['product_id']))
                    array_push($rules, ['field' => 'product_id', 'op' => 'in', 'data' => implode(",", $parameters['product_id'])]);
                else
                    array_push($rules, ['field' => 'product_id', 'op' => 'eq', 'data' => $parameters['product_id']]);
            }

            if (isset($parameters['parent']) && !empty($parameters['parent'])) {
                // 判断是否是叶级类目
                $category = AlibabacategoryService::getInstance()->getOne($parameters['parent']);
                if (empty($category))
                    throw new AlibabacategoryException(AlibabacategoryException::ALIBABACATEGORY_IS_NOT_EXISTS, AlibabacategoryException::ALIBABACATEGORY_IS_NOT_EXISTS_NO);
                if ($category['publishing'] == 0) {
                    array_push($rules, ['field' => 'category_id', 'op' => 'in',
                                        'data'  => implode(',', AlibabaCategory::getAllLeafCategoryByParentId($parameters['parent']))]);
                } else {
                    array_push($rules, ['field' => 'category_id', 'op' => 'eq', 'data' => $parameters['parent']]);
                }
            }

            if (isset($parameters['category']))
                array_push($rules, ['field' => 'category_id', 'op' => 'eq', 'data' => $parameters['category']]);

            if (isset($parameters['stats']))
                array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => $parameters['stats']]);
//            if ($from_api === true)
//                array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => 1]);

            if (isset($parameters['recommend']))
                array_push($rules, ['field' => 'recommennd', 'op' => 'eq', 'data' => $parameters['recommend']]);

            if (isset($parameters['redemption']))
                array_push($rules, ['field' => 'redemption', 'op' => 'eq', 'data' => $parameters['redemption']]);

            if (isset($parameters['name']))
                array_push($rules, ['field' => 'title', 'op' => 'nc', 'data' => '%' . $parameters['name'] . '%']);

            if (isset($parameters['keyword'])) {
                if (strpos($parameters['keyword'], ' ') === false)
                    array_push($rules, ['field' => 'title', 'op' => 'nc', 'data' => '%' . $parameters['keyword'] . '%']);
                else {
                    $groups_arr = [];
                    foreach (explode(' ', $parameters['keyword']) as $keyword) {
                        array_push($groups_arr, ['field' => 'title', 'op' => 'nc', 'data' => '%' . $keyword . '%']);
                    }
                    if (!empty($groups_arr))
                        $groups = [
                            [
                                'groupOp' => 'OR',
                                'rules' => $groups_arr
                            ]
                        ];
                }
                array_push($rules, ['field' => 'stats', 'op' => 'eq', 'data' => 1]);
            }
            if (!empty($rules))
                $condition = ['groupOp' => 'AND', 'rules' => $rules];
            if (!empty($groups))
                $condition['groups'] = $groups;

            $product = AlibabaproductService::getInstance()->getList(
                isset($parameters['page']) ? $parameters['page'] : 1,
                isset($parameters['page_size']) ? $parameters['page_size'] : 10,
                isset($parameters['sort']) ? $parameters['sort'] : 'desc',
                isset($parameters['order']) ? $parameters['order'] : 'created_at',
                $condition
            );
            if (empty($product['data']))
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);

            foreach ($product['data'] as $idx => $row) {
                if (null !== json_decode($row['price_ranges'], true)) {
                    $product['data'][$idx]['price_ranges'] = json_decode($row['price_ranges'], true);
                }else{
                    $product['data'][$idx]['price_ranges'] = [];
                }
                if (strpos($row['img_url'], 'http://') === false && strpos($row['img_url'], 'https://') === false)
                    $product['data'][$idx]['img_url'] = Registry::get('config')['application']['host'] . $row['img_url'];
                else {
                    if (strpos($row['img_url'], '_.webp') === false)
                        $product['data'][$idx]['img_url'] = str_replace(['.jpg', '.png', '.jpeg', '.gif'],
                            ['.jpg_.webp', '.png_.webp', '.jpeg_.webp', '.gif_.webp'], $row['img_url']);
                }
                if (strpos($row['images'], 'http://') === false && strpos($row['images'], 'https://') === false)
                    $product['data'][$idx]['images'] = Registry::get('config')['application']['host'] . $row['images'];
                else {
                    $product['data'][$idx]['images'] = $product['data'][$idx]['images'] . ',';
                    if (strpos($product['data'][$idx]['images'], '_.webp') === false)
                        $product['data'][$idx]['images'] = str_replace(['.jpg,', '.png,', '.jpeg,', '.gif,'],
                            ['.jpg_.webp,', '.png_.webp,', '.jpeg_.webp,', '.gif_.webp,'], $row['images']);
                    $product['data'][$idx]['images'] = substr($product['data'][$idx]['images'], 0, strrpos($product['data'][$idx]['images'], ','));
                }
                if (strpos($row['main_video'], 'http://') === false && strpos($row['main_video'], 'https://') === false)
                    $product['data'][$idx]['main_video'] = Registry::get('config')['application']['host'] . $row['main_video'];
            }

            // 后台调用 获取商品分类名称
            if ($from_api === false) {
                // 查询sku
                $product = AlibabaSku::getSkuByModules($product);

                $product = AlibabaCategory::getCategoriesByModules($product);
            }
            // 前端调用
            else {
                // 处理价格
                $product = self::getRealPlatformPrice($product);
                // 处理是否收藏
                $product = Member::getFavoursByProductLists($product);

                // 去除掉评分 返回的收藏量、点击量、浏览量、平台交易量均为假量+真量
                foreach ($product['data'] as $idx => $product_info) {
                    if (is_null($product_info['images']))
                        $product['data'][$idx]['images'] = '';
                    //重复处理，去除
//                    else {
//                        if (strpos($product_info['images'], 'http://') === false && strpos($product_info['images'], 'https://') === false)
//                            $product['data'][$idx]['images'] = Registry::get('config')['application']['host'] . $product_info['images'];
//                        else
//                            $product['data'][$idx]['images'] = str_replace(['.jpg,', '.png,', '.jpeg,', '.gif,'],
//                                ['.jpg_.webp,', '.png_.webp,', '.jpeg_.webp,', '.gif_.webp,'], $product_info['images']);
//                    }
//                    if (strpos($product_info['img_url'], 'http://') === false && strpos($product_info['img_url'], 'https://') === false)
//                        $product['data'][$idx]['img_url'] = Registry::get('config')['application']['host'] . $product_info['img_url'];
//                    else
//                        $product['data'][$idx]['img_url'] = str_replace(['.jpg', '.png', '.jpeg', '.gif'],
//                            ['.jpg_.webp', '.png_.webp', '.jpeg_.webp', '.gif_.webp'], $product_info['img_url']);
//                    if (null !== json_decode($product_info['price_ranges'], true))
//                        $product['data'][$idx]['price_ranges'] = json_decode($product_info['price_ranges'], true);
//                    else
//                        $product['data'][$idx]['price_ranges'] = [];
                    else {
                        /*if (strpos($product_info['images'], 'http://') === false && strpos($product_info['images'], 'https://') === false)
                            $product['data'][$idx]['images'] = Registry::get('config')['application']['host'] . $product_info['images'];
                        else
                            $product['data'][$idx]['images'] = str_replace(['.jpg,', '.png,', '.jpeg,', '.gif,'],
                                ['.jpg_.webp,', '.png_.webp,', '.jpeg_.webp,', '.gif_.webp,'], $product_info['images']);*/
                    }
                    /*if (strpos($product_info['img_url'], 'http://') === false && strpos($product_info['img_url'], 'https://') === false)
                        $product['data'][$idx]['img_url'] = Registry::get('config')['application']['host'] . $product_info['img_url'];
                    else
                        $product['data'][$idx]['img_url'] = str_replace(['.jpg', '.png', '.jpeg', '.gif'],
                            ['.jpg_.webp', '.png_.webp', '.jpeg_.webp', '.gif_.webp'], $product_info['img_url']);*/
                    if (null !== json_decode($product_info['price_ranges'], true))
                        $product['data'][$idx]['price_ranges'] = json_decode($product_info['price_ranges'], true);
                    else
                        $product['data'][$idx]['price_ranges'] = [];

                    unset($product['data'][$idx]['price_score']);
                    unset($product['data'][$idx]['sales_score']);
                    unset($product['data'][$idx]['favours_score']);
                    unset($product['data'][$idx]['sales_in_30_days_score']);
                    unset($product['data'][$idx]['click_score']);
                    unset($product['data'][$idx]['order_score']);
                    $product['data'][$idx]['favours'] += $product['data'][$idx]['fake_favours'];
                    unset($product['data'][$idx]['fake_favours']);
                    $product['data'][$idx]['clicks'] += $product['data'][$idx]['fake_clicks'];
                    unset($product['data'][$idx]['fake_clicks']);
                    $product['data'][$idx]['views'] += $product['data'][$idx]['fake_views'];
                    unset($product['data'][$idx]['fake_views']);
                    $product['data'][$idx]['platform_sales'] += $product['data'][$idx]['fake_platform_sales'];
                    unset($product['data'][$idx]['fake_platform_sales']);
                    $product['data'][$idx]['sales'] = $product['data'][$idx]['platform_sales'];
                }
            }

            return $product;
        } catch (AlibabacategoryException $e) {
            throw $e;
        } catch (AlibabaproductException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() === ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() === ModelException::DATA_NOT_EXISTS)
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 根据1688 product_id查找alibabaproduct表的数据
     * @param $product_id
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getProductByProductId($product_id)
    {
        try {
            if (empty($product_id))
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY, AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY_NO);
            // 判断商品是否存在
            $exists = AlibabaproductService::getInstance()->getOne($product_id);

            // 商品不存在抛错
            if (empty($exists))
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_IS_NOT_EXISTS_NO);
        } catch (AlibabaproductException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * 编辑1688 product
     * @param array $parameters
     * @return array|mixed|null
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     * @throws \models\Exception\Business\BookingException
     */
    static public function editProduct($parameters = [])
    {
        try {
            if (!isset($parameters['product_id']) || empty($parameters['product_id']))
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY, AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY_NO);

            $update_arr = [];
            if (isset($parameters['category_id']))
                $update_arr['category_id'] = $parameters['category_id'];
            if (isset($parameters['title']))
                $update_arr['title'] = $parameters['title'];
            if (isset($parameters['description']))
                $update_arr['description'] = $parameters['description'];

            if (isset($parameters['img_url'])) {
                if (strpos($parameters['img_url'], Registry::get('config')['application']['host']) !== false)
                    $update_arr['img_url'] = str_replace(Registry::get('config')['application']['host'], '', $parameters['img_url']);
                else
                    $update_arr['img_url'] = $parameters['img_url'];
            }

            if (isset($parameters['images'])) {
                if (strpos($parameters['images'], Registry::get('config')['application']['host']) !== false)
                    $update_arr['images'] = str_replace(Registry::get('config')['application']['host'], '', $parameters['images']);
                else
                    $update_arr['images'] = $parameters['images'];
            }
            if (isset($parameters['quality_level']))
                $update_arr['quality_level'] = $parameters['quality_level'];
            if (isset($parameters['supplier_loginId']))
                $update_arr['supplier_loginId'] = $parameters['supplier_loginId'];
            if (isset($parameters['main_video'])) {
                if (strpos($parameters['main_video'], Registry::get('config')['application']['host']) === false)
                    $update_arr['main_video'] = $parameters['main_video'];
                else
                    $update_arr['main_video'] = str_replace(Registry::get('config')['application']['host'], '', $parameters['main_video']);
            }
            if (isset($parameters['product_cargo_number']))
                $update_arr['product_cargo_number'] = $parameters['product_cargo_number'];
            if (isset($parameters['reference_price']))
                $update_arr['reference_price'] = $parameters['reference_price'];
            if (isset($parameters['reference_price']))
                $update_arr['reference_price'] = $parameters['reference_price'];
            if (isset($parameters['alibaba_stats']))
                $update_arr['alibaba_stats'] = $parameters['alibaba_stats'];
            if (isset($parameters['support_online_trade']))
                $update_arr['support_online_trade'] = $parameters['support_online_trade'];
            if (isset($parameters['mix_whole_sale']))
                $update_arr['mix_whole_sale'] = $parameters['mix_whole_sale'];
            if (isset($parameters['price_auth']))
                $update_arr['price_auth'] = $parameters['price_auth'];
            if (isset($parameters['price_ranges']))
                $update_arr['price_ranges'] = $parameters['price_ranges'];
            if (isset($parameters['amount_on_sale']))
                $update_arr['amount_on_sale'] = $parameters['amount_on_sale'];
            if (isset($parameters['unit']))
                $update_arr['unit'] = $parameters['unit'];
            if (isset($parameters['min_order_quantity']))
                $update_arr['min_order_quantity'] = $parameters['min_order_quantity'];
            if (isset($parameters['batch_number']))
                $update_arr['batch_number'] = $parameters['batch_number'];
            if (isset($parameters['sell_unit']))
                $update_arr['sell_unit'] = $parameters['sell_unit'];
            if (isset($parameters['quote_type']))
                $update_arr['quote_type'] = $parameters['quote_type'];
            if (isset($parameters['consign_price']))
                $update_arr['consign_price'] = $parameters['consign_price'];
            if (isset($parameters['cps_suggest_price']))
                $update_arr['cps_suggest_price'] = $parameters['cps_suggest_price'];
            if (isset($parameters['channel_price']))
                $update_arr['channel_price'] = $parameters['channel_price'];

            if (isset($parameters['recommennd']))
                $update_arr['recommennd'] = $parameters['recommennd'];
            if (isset($parameters['stats'])) {
                $update_arr['stats'] = $parameters['stats'];
                try {
                    $action = '取关';
                    $action_res = null;
                    if ($update_arr['stats'] == 1) {
                        $action_res = Alibaba::getProductFollow($parameters['product_id']);
                        $action = '关注';
                    } else if ($update_arr['stats'] == 0)
                        $action_res = Alibaba::unFollowProduct($parameters['product_id']);

                    if (!is_null($action_res))
                        Registry::get('alibaba_log')->debug($parameters['product_id'] . $action . json_encode($action_res));
                    else
                        Registry::get('alibaba_log')->debug($parameters['product_id'] . '非法stats' . $parameters['stats'] . '-' . $action_res);
                } catch (\Exception $e) {
                    Registry::get('alibaba_log')->err($parameters['product_id'] . $action . '失败');
                }
            }
            if (isset($parameters['redemption']))
                $update_arr['redemption'] = $parameters['redemption'];
            if (isset($parameters['platform_price']))
                $update_arr['platform_price'] = $parameters['platform_price'];
            if (isset($parameters['integral']))
                $update_arr['integral'] = $parameters['integral'];
            if (isset($parameters['leaf_parent_id']) && !empty($parameters['leaf_parent_id']))
                $update_arr['category_id'] = $parameters['leaf_parent_id'];
            else if (isset($parameters['sub_parent_id']) && !empty($parameters['sub_parent_id']))
                $update_arr['category_id'] = $parameters['sub_parent_id'];

            if (isset($parameters['platform_sales']))
                $update_arr['platform_sales'] = $parameters['platform_sales'];
            if (isset($parameters['fake_platform_sales']))
                $update_arr['fake_platform_sales'] = $parameters['fake_platform_sales'];
            if (isset($parameters['sales_in_30_days']))
                $update_arr['sales_in_30_days'] = $parameters['sales_in_30_days'];
            if (isset($parameters['fake_favours']))
                $update_arr['fake_favours'] = $parameters['fake_favours'];
            if (isset($parameters['favours']))
                $update_arr['favours'] = $parameters['favours'];
            if (isset($parameters['fake_views']))
                $update_arr['fake_views'] = $parameters['fake_views'];
            if (isset($parameters['views']))
                $update_arr['views'] = $parameters['views'];
            if (isset($parameters['fake_clicks']))
                $update_arr['fake_clicks'] = $parameters['fake_clicks'];
            if (isset($parameters['clicks']))
                $update_arr['clicks'] = $parameters['clicks'];

            if (isset($parameters['rebate_integral']))
                $update_arr['rebate_integral'] = $parameters['rebate_integral'];
            if (isset($parameters['parent_rebate_integral']))
                $update_arr['parent_rebate_integral'] = $parameters['parent_rebate_integral'];
            if (isset($parameters['sub_rebate_integral']))
                $update_arr['sub_rebate_integral'] = $parameters['sub_rebate_integral'];
            if (isset($parameters['is_booking'])) {
                $update_arr['is_booking'] = $parameters['is_booking'];
                Booking::chkMachineCoupon($parameters['product_id'], $update_arr['is_booking'] == 1);
            }

            if (!empty($update_arr)) {
                $update_arr['updated_at'] = date('Y-m-d H:i:s', time());
                $alibaba_product          = AlibabaproductService::getInstance()->update($update_arr, $parameters['product_id']);
                // 删除redis中的数据
                Registry::get('redis_string')->deleteString('alibaba_product:' . $parameters['id']);
            } else
                $alibaba_product = AlibabaproductService::getInstance()->getOne($parameters['product_id']);

            return $alibaba_product;
        } catch (AlibabaproductException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            if ($e->getCode() == ModelDriverException::DRIVER_EXCEPTION_MSG_NO)
                throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_EDIT_FAILURE, AlibabaproductException::ALIBABAPRODUCT_EDIT_FAILURE_NO);
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }

    /**
     * 将采集来的1688 product数据入库
     * @param array $product_arr
     * @param boolean $not_exists_insert
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function collectProduct($product_arr = [], $not_exists_insert = true)
    {
        try {
            $update_data_arr = $insert_data_arr = [];
            $product_id_arr  = array_column($product_arr, 'product_id');
            // 查询商品是否存在
            if (count($product_arr) == 1) {
                $exists['data'][] = AlibabaproductService::getInstance()->getOne(implode('', $product_id_arr));
            } else {
                $condition = ['groupOp' => 'AND', 'rules' => [
                    ['field' => 'product_id', 'op' => 'in', 'data' => implode(',', $product_id_arr)]]];
                $exists    = AlibabaproductService::getInstance()->getList(1, count($product_arr), 'desc', 'product_id',
                    $condition);
            }

            if (!empty($exists['data'])) {
                $exists_product_id_arr = array_column($exists['data'], 'product_id');
                foreach ($product_arr as $idx => $product_info) {
                    // 已存在的商品写入更新数据
                    if (in_array($product_info['product_id'], $exists_product_id_arr)) {
                        // 批量修改不修改商品标题
                        if (isset($product_info['title']))
                            unset($product_info['title']);
                        // 批量修改不修改商品图集
                        if (isset($product_info['images']))
                            unset($product_info['images']);
                        // 批量修改不修改商品主图
                        if (isset($product_info['img_url']))
                            unset($product_info['img_url']);
                        array_push($update_data_arr, $product_info);
                    } // 不存在的商品写入插入数组
                    else {
                        array_push($insert_data_arr, $product_info);
                    }
                }
            } else
                $insert_data_arr = $product_arr;

            // 更新数组存在
            if (!empty($update_data_arr)) {
                // 更新数组长度大于1，批量插入
                if (count($update_data_arr) > 1)
                    AlibabaproductService::getInstance()->batchUpdate($update_data_arr);
                // 更新数组长度等于1，单条更新
                else {
                    $update_arr = array_values($update_data_arr);
                    $update_arr = $update_arr[0];
                    $product_id = $update_arr['product_id'];
                    AlibabaproductService::getInstance()->update($update_arr, $product_id);
                }
            }

            // 插入数据存在
            if (!empty($insert_data_arr) && $not_exists_insert === true)
                // 批量插入
                AlibabaproductService::getInstance()->batchInsert($insert_data_arr);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 根据商品编号、收货省份、商品数量，计算运费
     * @param $product_id
     * @param $province
     * @param $num
     * @return array
     * @throws AlibabacategoryException
     * @throws AlibabaproductException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getShippingFeeByProductIdProvince($product_id, $province, $num) {
        $product = AlibabaProduct::getProduct(['id' => $product_id, 'from_api' => true]);
        if ($product['data'][0]['stats'] != 1)
            throw new AlibabaproductException(AlibabaproductException::ALIBABAPRODUCT_NOT_EXISTS, AlibabaproductException::ALIBABAPRODUCT_NOT_EXISTS_NO);
        $product = $product['data'][0];

        // 根据省份查找运费模板
        $shipping = AlibabashippingService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
            ['field' => 'product_id', 'op' => 'eq', 'data' => $product_id],
            ['field' => 'to_area_code_text', 'op' => 'nc', 'data' => '%' . $province . '%']]]);
        // 1688卖家并没有根据指定省份名称设置运费模板时，查找默认运费模版，即to_area_code_text为空的运费模板
        if (empty($shipping)) {
            $shipping = AlibabashippingService::getInstance()->getOne(['groupOp' => 'AND', 'rules' => [
                ['field' => 'product_id', 'op' => 'eq', 'data' => $product_id],
                ['field' => 'to_area_code_text', 'op' => 'nc', 'data' => '']
            ]]);
        }
        /*$shipping = AlibabashippingService::getInstance()->getOne([
            'groupOp' => 'OR',
            'groups' => [
                [
                    'groupOp' => 'AND',
                    'rules' => [
                        ['field' => 'product_id', 'op' => 'eq', 'data' => $product_id],
                        ['field' => 'to_area_code_text', 'op' => 'nc', 'data' => '%' . $province . '%']
                    ]
                ],
                [
                    'groupOp' => 'AND',
                    'rules' => [
                        ['field' => 'product_id', 'op' => 'eq', 'data' => $product_id],
                        ['field' => 'to_area_code_text', 'op' => 'nc', 'data' => '']
                    ]
                ]
            ]
        ]);*/

        $system = SystemService::getInstance()->getOne(1);
        $increment_fee = $system['default_post_fee'];
        // 不存在运费模板时，默认收取用户至少6元的运费
        if (empty($shipping)) {
            $fee = $increment_fee < 6 ? 6 : $increment_fee;
        } else {
            $unit_weight = $shipping['unit_weight'];
            // 计件类型为计重时(charge_type == 0)时，需要计算商品总重量(total_weight = unit_weight * num)
            // 计件类型为计件时(charge_type == 1)时，需要计算商品总数量(total_weight = num)
            $total_weight = $num * ($shipping['charge_type'] == 0 ? $unit_weight : 1);
            // 根据next_unit的值来计算商品运费总共需要next_unit_fee
            $next_unit_times = ceil(($total_weight - $shipping['first_unit']) / $shipping['next_unit']);
            $fee = $shipping['first_unit_fee'];
            for ($i = 0; $i < $next_unit_times; $i++) {
                $fee += $shipping['next_unit_fee'];
            }

            $real_fee = sprintf('%.2f', $fee / 100) + $increment_fee;
        }


        return [
            'product_id' => $product_id,
            'num' => $num,
            'unit_weight' => $unit_weight,
            'total_weight' => $total_weight,
            'first_unit' => $shipping['first_unit'],
            'first_unit_fee' => sprintf('%.2f', $shipping['first_unit_fee'] / 100),
            'real_first_unit_fee' => sprintf('%.2f', $shipping['first_unit_fee'] / 100) + $increment_fee,
            'next_unit' => $shipping['next_unit'],
            'next_unit_fee' => sprintf('%.2f', $shipping['next_unit_fee'] / 100),
            'real_next_unit_fee' => sprintf('%.2f', $shipping['next_unit_fee'] / 100) + $increment_fee,
            'fee' => sprintf('%.2f', $fee / 100),
            'real_fee' => $real_fee < 6 ? 6 : $real_fee
        ];

    }
}
